<?php
require 'libs/rb-mysql.php';

R::setup('mysql:host=43.142.143.8;port=8306;dbname=bot', 'hunk7095', '123456');

//$timezone = R::dispense('timezones');

$timezones = R::findAll('timezones');

function countryToFlag($countryCode): string
{
    $flag = '';
    foreach (str_split(strtoupper($countryCode)) as $char) {
        $codePoint = 0x1F1E6 + ord($char) - ord('A');  // 计算区域指示符
        $flag .= mb_chr($codePoint, 'UTF-8');
    }
    return $flag;
}

$tzMap = [];
foreach ($timezones as $tz) {
    $offset = $tz->offset;
    $offsetList = explode(':', $offset);
    if (count($offsetList) === 2) {
        $offset = $offsetList[0] . '.' . ((intval($offsetList[1]) / 60) * 100);
    }
    $offset = str_replace('+', '', $offset);

    if (!isset($tzMap[$offset])) {
        $tzMap[$offset] = [
            'offset' => $offset,
            'countries' => []
        ];
    }
    $offsetData = $tzMap[$offset];

    $countryCode = $tz->code_alpha2;

    if (!isset($offsetData['countries'][$countryCode])) {
        $offsetData['countries'][$countryCode] = [
            'country_code' => $countryCode,
            'country_name' => $tz->country_name,
            'flag' => countryToFlag($countryCode),
            'sort' => $tz->sort,
            'timezone_id' => $tz->tz_id,
            'zones' => [],
        ];
    }

    if ($tz->sort < $offsetData['countries'][$countryCode]['sort']) {
        $offsetData['countries'][$countryCode]['sort'] = $tz->sort;
    }

    $offsetData['countries'][$countryCode]['zones'][] = [
        'title' => $tz->title,
        'timezone_id' => $tz->tz_id,
        'is_capital' => $tz->is_capital,
        'sort' => $tz->sort,
    ];

    $tzMap[$offset] = $offsetData;
}

$tzArr = [];
foreach ($tzMap as $k => $v) {
    uasort($v['countries'], function ($a, $b) {
        return $a['sort'] <=> $b['sort'];
    });
    $countries = array_values($v['countries']);
    $tzArr[] = [
        'offset' => $k,
        'timezone_id' => $countries[0]['timezone_id'],
        'countries' => $countries
    ];
}


uasort($tzArr, function ($a, $b) {
    if ($a['offset'] === $b['offset']) {
        return 0;
    } elseif ($a['offset'] > $b['offset']) {
        return 1;
    } else {
        return -1;
    }
});

file_put_contents('tz2.js',
    'const tzArr = ' . json_encode(array_values($tzArr),
        JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n");

//file_put_contents('tz2.js',
//    'const tzArr = ' . json_encode(array_values($tzArr),
//        JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ";\n");